package cn.ac.iie.di.ban.jr.rest.util;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;

/**
 * Created by Black-Laptop on 8/17/2017.
 */
public class httpUtils {

    public static Logger LOG = Logger.getLogger(httpUtils.class);

    public static String post(String url, String body) throws Exception {

        URL restServiceURL;
        HttpURLConnection httpConnection = null ;
        try {
            restServiceURL = new URL(url);
            httpConnection= (HttpURLConnection) restServiceURL.openConnection();
            httpConnection.setRequestMethod("POST");
            httpConnection.setRequestProperty("Accept", "application/json");
            httpConnection.setRequestProperty("Content-Type", "application/json");
            httpConnection.setDoOutput(true);
            httpConnection.connect();
            OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream(), "UTF-8");
            out.append(body);
//            LOG.debug(out.toString());
            out.flush();
            out.close();
            LOG.debug(body);
//            LOG.debug(JSONArray.parseArray(body));
            if (httpConnection.getResponseCode() != 200) {
                BufferedReader responseBuffer = new BufferedReader(
                        new InputStreamReader((httpConnection.getErrorStream())));
                StringBuffer errorMess=new StringBuffer();
                String output;
                while ((output = responseBuffer.readLine()) != null) {
                    errorMess.append(output);
                }
                throw new RuntimeException("HTTP POST Request Failed with Error code : "
                        + httpConnection.getResponseCode() + errorMess.toString());
            }
            BufferedReader responseBuffer = new BufferedReader(
                    new InputStreamReader((httpConnection.getInputStream())));
            StringBuffer resultMess=new StringBuffer();
            String output;
            while ((output = responseBuffer.readLine()) != null) {
                resultMess.append(output);
            }
            return resultMess.toString();
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }finally {
            if(httpConnection!=null){
                httpConnection.disconnect();
            }
        }
    }

    /**
     * 发送get请求
     * @param url    路径
     * @return
     */
    public static String httpGet(String url){
        //get请求返回结果
        String strResult = null;
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            //发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = null;
            try {
                response = client.execute(request);
            } catch (IOException e) {
                LOG.error(ExceptionUtils.getFullStackTrace(e));
            }

            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                strResult = EntityUtils.toString(response.getEntity());
                /**把json字符串转换成json对象**/
                url = URLDecoder.decode(url, "UTF-8");
            } else {
                LOG.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            LOG.error("get请求提交失败:" + url, e);
        }
        return strResult;
    }
}
